﻿using System.IO;
using UnityEngine.UI;
using UnityEngine;
using LitJson;
using System.Text;

public class BookShelf : BookDetails 
{

	public BookShelf(string path,string title,string author,string cellPath,string parentName)
    {
        this.theCoverPath = path;
        this.txtTitle = title;
        this.txtAuthor = author;
        this.cellPath = cellPath;
        this.cellParentName = parentName;

    }

	public BookShelf(string path,string title,string author)
	{
		this.theCoverPath = path;
		this.txtTitle = title;
		this.txtAuthor = author;
	}

	public BookShelf()
	{
		
	}

	public void AddBookShelf()
	{
		string jPath = Application.streamingAssetsPath + "/BookShelfList.json";
		StreamWriter sw;
		if (!File.Exists(jPath))
		{
			sw = File.CreateText (jPath);
		}
		else
		{
			sw = File.AppendText (jPath);
		}

		StringBuilder sb = new StringBuilder ();
		JsonWriter writer = new JsonWriter (sb);

		string json = File.ReadAllText(jPath);
		JsonData jd = JsonMapper.ToObject (json);

		int count = int.Parse (jd ["Count"].ToString ());

		writer.WriteObjectStart ();
		writer.WritePropertyName ("Count");
		writer.Write (count.ToString ());

		JsonData jdItems = jd ["details"];

		writer.WritePropertyName ("details");
		writer.WriteArrayStart ();
		for(int i=0;i<jdItems.Count;i++)
		{

			string path=jdItems [i] ["path"].ToString();
			string title = jdItems [i] ["title"].ToString ();
			string author = jdItems [i] ["author"].ToString ();

			writer.WriteObjectStart ();
			writer.WritePropertyName ("path");
			writer.Write (path);
			writer.WritePropertyName ("title");
			writer.Write (title);
			writer.WritePropertyName ("author");
			writer.Write (author);
			writer.WriteObjectEnd ();

		}

		writer.WriteObjectStart ();
		writer.WritePropertyName ("path");
		writer.Write (this.theCoverPath);
		writer.WritePropertyName ("title");
		writer.Write (this.txtTitle);
		writer.WritePropertyName ("author");
		writer.Write (this.txtAuthor);
		writer.WriteObjectEnd ();

		writer.WriteArrayEnd ();
		writer.WriteObjectEnd ();
		Debug.Log (sb);

		sw.WriteLine (sb.ToString ());
		sw.Close ();
	}
		
		

    
}
